package se.liu.oschi129.game.objects.items;

import java.awt.Shape;
import java.awt.geom.Rectangle2D;

import se.liu.oschi129.animation.Animation;
import se.liu.oschi129.game.objects.ObjectPlayer;
import se.liu.oschi129.shapefactory.ShapeFactory;
import se.liu.oschi129.world.model.World;
import se.liu.oschi129.world.objects.WorldMovableObject;
import se.liu.oschi129.world.objects.WorldObject;

/**
 * This is player powerup
 */
public abstract class ObjectPowerup extends WorldMovableObject implements CollectibleObject {
	
	// The timer used when the powerup pops out of a block
	private int timer;
	
	// Whatever this object is under creation or not
	private boolean creation;
	
	/**
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 * - - - - - - - - - - - - Constructors - - - - - - - - - - - 
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 */
	
	public ObjectPowerup(Animation animation, double x, double y, double width, double height) {
		super(Type.SOFT, animation,true,x,y,width, height);
		setVerticalSpeed(-2);
		setDepth(1);
		setMaskFactory(new DefaultMask());
		creation = true;
		timer = 0;
	}
	
	public ObjectPowerup(boolean still, Animation animation, double x, double y, double width, double height) {
		this(animation, x, y, width, height);
		if (still) {
			setVerticalSpeed(0);
			creation = false;
		}
	}
	
	/**
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 * - - - - - - - - - - - Public methods - - - - - - - - - -
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 */
	
	@Override public void performStepAction(World world) {
		super.performStepAction(world);
		if (creation) {
			// The powerup is moving up from the block
			if (timer == 8) {
				setVerticalSpeed(0);
				WorldObject player = world.objectExists(ObjectPlayer.class);
				if (player != null && player.getX() > getX())
					setHorizontalSpeed(-2);
				else
					setHorizontalSpeed(2);
				creation = false;
			} else {
				timer++;
			}
		} else {
			if (getPhysicalRules() == null)
				setPhysicalRules(world.getPhysicalRules());
			realizeGravity(world);
			if (!world.placeFree(this, getX() + getHorizontalSpeed(), getY())) {
				setHorizontalSpeed(-getHorizontalSpeed());
			}
		}
	}
	
	/**
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 * - - - - - - - - - - Private classes - - - - - - - - - - -
	 * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
	 */
	
	/** Defines the default mask for the enemy*/
	private class DefaultMask implements ShapeFactory {
		
		public Shape makeShape(double x, double y, double width, double height) {
			return new Rectangle2D.Double(x+4,y,width-8,height);
		}
		
	}
	
}
